#include "loginwindow.h"
#include <QDebug>
#include "sfts_client_api.h"
#include "gui_bridge.h"
#include "client_wrapper.h"
#include "register_dialog.hpp"

// If you have C client functions for login
// extern "C" { // Now in sfts_client_api.h
// int client_login_attempt(const char *username, const char *password);
// }

LoginWindow::LoginWindow(QWidget *parent) : QDialog(parent), m_clientWrapper(nullptr)
{
    setupUi();
    setWindowTitle(tr("用户登录"));

    connect(m_loginButton, &QPushButton::clicked, this, &LoginWindow::handleLoginAttempt);
    connect(m_cancelButton, &QPushButton::clicked, this, &LoginWindow::handleCancel);

    // 连接到GuiSignaler获取登录结果
    connect(GuiSignaler::instance(), &GuiSignaler::loginResultReceived,
            this, &LoginWindow::onLoginResult, Qt::QueuedConnection);
}

LoginWindow::LoginWindow(ClientWrapper *clientWrapper, QWidget *parent)
    : QDialog(parent), m_clientWrapper(clientWrapper)
{
    setupUi();
    setWindowTitle(tr("用户登录"));

    connect(m_loginButton, &QPushButton::clicked, this, &LoginWindow::handleLoginAttempt);
    connect(m_cancelButton, &QPushButton::clicked, this, &LoginWindow::handleCancel);
    connect(m_registerButton, &QPushButton::clicked, this, &LoginWindow::handleRegisterClicked);

    if (m_clientWrapper)
    {
        connect(m_clientWrapper, &ClientWrapper::loginResult,
                this, &LoginWindow::onLoginResult, Qt::QueuedConnection);
    }
    else
    {
        connect(GuiSignaler::instance(), &GuiSignaler::loginResultReceived,
                this, &LoginWindow::onLoginResult, Qt::QueuedConnection);
    }
}

LoginWindow::~LoginWindow()
{
    // 清理资源
}

void LoginWindow::setupUi()
{
    m_usernameLabel = new QLabel(tr("用户名:")); // "Username:"
    m_usernameLineEdit = new QLineEdit;
    m_passwordLabel = new QLabel(tr("密码:")); // "Password:"
    m_passwordLineEdit = new QLineEdit;
    m_passwordLineEdit->setEchoMode(QLineEdit::Password);

    m_loginButton = new QPushButton(tr("登录"));  // "Login"
    m_cancelButton = new QPushButton(tr("取消")); // "Cancel"
    m_registerButton = new QPushButton(tr("注册"));

    QVBoxLayout *mainLayout = new QVBoxLayout(this);

    QHBoxLayout *usernameLayout = new QHBoxLayout;
    usernameLayout->addWidget(m_usernameLabel);
    usernameLayout->addWidget(m_usernameLineEdit);
    mainLayout->addLayout(usernameLayout);

    QHBoxLayout *passwordLayout = new QHBoxLayout;
    passwordLayout->addWidget(m_passwordLabel);
    passwordLayout->addWidget(m_passwordLineEdit);
    mainLayout->addLayout(passwordLayout);

    QHBoxLayout *buttonLayout = new QHBoxLayout;
    buttonLayout->addStretch();
    buttonLayout->addWidget(m_registerButton);
    buttonLayout->addWidget(m_loginButton);
    buttonLayout->addWidget(m_cancelButton);
    mainLayout->addLayout(buttonLayout);

    setLayout(mainLayout);
    setModal(true); // Make it a modal dialog
}

void LoginWindow::handleLoginAttempt()
{
    QString username = m_usernameLineEdit->text();
    QString password = m_passwordLineEdit->text();

    if (username.isEmpty() || password.isEmpty())
    {
        QMessageBox::warning(this, tr("登录失败"), tr("用户名和密码不能为空。"));
        return;
    }

    // 禁用登录按钮防止重复点击
    m_loginButton->setEnabled(false);
    m_passwordLineEdit->setEnabled(false);
    m_usernameLineEdit->setEnabled(false);

    // 使用ClientWrapper或直接调用C接口发送登录请求
    if (m_clientWrapper)
    {
        m_clientWrapper->login(username, password);
    }
    else
    {
        // 直接调用C接口
        int ret = sfts_client_login(username.toStdString().c_str(), password.toStdString().c_str());
        if (ret != 0)
        {
            // 登录请求发送失败
            QMessageBox::critical(this, tr("登录请求失败"),
                                  tr("无法发送登录请求到后端服务。请检查客户端状态。"));
            m_loginButton->setEnabled(true);
            m_passwordLineEdit->setEnabled(true);
            m_usernameLineEdit->setEnabled(true);
        }
    }
    // 实际登录结果将通过onLoginResult槽函数处理
}

void LoginWindow::onLoginResult(bool success, const QString &messageOrUser)
{
    // 重新启用UI元素
    m_loginButton->setEnabled(true);
    m_passwordLineEdit->setEnabled(true);
    m_usernameLineEdit->setEnabled(true);

    if (success)
    {
        m_lastSuccessfulUsername = messageOrUser; // Store the username
        QMessageBox::information(this, tr("登录成功"), tr("欢迎, %1!").arg(m_lastSuccessfulUsername));
        emit loginSuccessful(m_lastSuccessfulUsername);
        accept();
    }
    else
    {
        m_lastSuccessfulUsername.clear(); // Clear on failure
        QMessageBox::critical(this, tr("登录失败"), messageOrUser);
        m_passwordLineEdit->clear();
        m_passwordLineEdit->setFocus();
    }
}

void LoginWindow::handleCancel()
{
    // 如果正在进行登录请求，可能需要通知C后端，但对于取消按钮通常不需要
    emit loginCancelled();
    reject(); // 关闭对话框
}

void LoginWindow::handleRegisterClicked()
{
    RegisterDialog registerDialog(m_clientWrapper, this);

    registerDialog.exec();
}

QString LoginWindow::getLastSuccessfulUsername() const
{
    return m_lastSuccessfulUsername;
}